package controllers

import (
	"chat/app/repositories"
	"log"
	"strconv"
	"time"
)

type ChatController struct {
	baseController
	repositories.ChatRepository
}

func (this ChatController) NestPrepare() {

}

//前端时间戳转换， 数据库时区错误
func (this *ChatController) Get() {
	list := this.MemberRepository.GetOnlineList(&this.Controller)

	log.Println(time.Now())
	this.Data["title"] = "chat"
	this.Data["lists"] = list
	this.TplName = "chat/index.tpl"
}

func (this *ChatController) Room() {

	user_id_str := this.Input().Get("uid")

	user_id, err := strconv.Atoi(user_id_str)
	log.Println(user_id_str, "====", user_id)
	if err != nil {
		this.Data["json"] = err.Error()
	}

	this.Data["json"] = this.MemberRepository.GetRooms(user_id)

	this.ServeJSON()
}

func (this *ChatController) History() {

	chat_id, _ := this.GetInt64("chat_id")
	uid, _ := this.GetInt64("uid")
	messages, _ := this.ChatRepository.GetHistoryMessage(chat_id, uid)
	this.Data["json"] = messages
	this.ServeJSON()
}

func (this *ChatController) GetHistoryByBuyer() {

	shopuid, _ := this.GetInt64("shopuid")
	uid, _ := this.GetInt64("uid")
	chat_id := this.GetChatServerId(shopuid, uid)
	messages, _ := this.ChatRepository.GetHistoryMessage(chat_id, shopuid)

	arr := make([]interface{}, len(messages))
	for i, messageItem := range messages {
		msg := make(map[string]interface{})
		msg["msg"] = messageItem.Msg
		msg["id"] = messageItem.Id
		msg["if_read"] = messageItem.IfRead
		msg["chat_id"] = messageItem.ChatId
		msg["member_id"] = messageItem.MemberId
		msg["create_at"] = messageItem.CreatedAt.Format("2006-01-02 15:04:05")
		msg["read_at"] = messageItem.ReadAt.Format("2006-01-02 15:04:05")
		arr[i] = msg
	}
	this.Data["json"] = arr
	this.ServeJSON()
}
func (this *ChatController) GetHistoryByShoper() {

	shopuid, _ := this.GetInt64("shopuid")
	uid, _ := this.GetInt64("uid")
	chat_id := this.GetChatServerId(shopuid, uid)
	messages, _ := this.ChatRepository.GetHistoryMessage(chat_id, uid)

	arr := make([]interface{}, len(messages))
	for i, messageItem := range messages {
		msg := make(map[string]interface{})
		msg["msg"] = messageItem.Msg
		msg["id"] = messageItem.Id
		msg["if_read"] = messageItem.IfRead
		msg["chat_id"] = messageItem.ChatId
		msg["member_id"] = messageItem.MemberId
		msg["create_at"] = messageItem.CreatedAt.Format("2006-01-02 15:04:05")
		msg["read_at"] = messageItem.ReadAt.Format("2006-01-02 15:04:05")
		arr[i] = msg
	}
	this.Data["json"] = arr

	this.ServeJSON()
}

func (this *ChatController) Delete() {

	chat_id, _ := this.GetInt64("chat_id")
	uid, _ := this.GetInt64("uid")

	this.Data["json"] = this.ChatRepository.DeleteChat(chat_id, uid)
	this.ServeJSON()
}
